package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * @author Tsuchi
 * @description TODO
 * @date 2024/12/20 18:59
 */

// 转换所有字符串为枚举类对象
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String,BaseEnum> {
	@Override
	public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
		return new Converter<String, T>() {
			@Override
			public T convert(String source) {
				// 获取所有枚举常量/对象
				for (T enumConstant : targetType.getEnumConstants()) {


					// 找到匹配的枚举构造并返回对应code的枚举对象
					if(enumConstant.getCode().equals(Integer.valueOf(source))){
						return enumConstant;
					}
				}
				return null;
			}
		};
	}
}
